package interview

import (
	"data/config"
	"data/view/approval"
	"data/view/auth"
	"data/view/auth/auth_const"
	"data/view/common"
	"data/view/oplog"
	"data/view/user"
	"public/message"
	"public/mysqldb"
	"public/tools"
	"strings"
	"time"

	"github.com/ant0ine/go-json-rest/rest"
)

//创建面试单
func CreateSheet(w rest.ResponseWriter, r *rest.Request) {
	var req CreateSheetParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token, req.Apply_no) || len(req.Interviewer) == 0 || len(req.Assistant) == 0 {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := user.GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}
	u, bb := user.GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}
	//权限检验
	b := auth.CheckRoleAuth(u.Business_role, auth_const.M_6, auth_const.L_A, auth_const.L_C)
	if !b {
		w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
		return
	}
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	//判断审批单号是否有效
	var event approval.Approval_event_tbl
	orm.Where("apply_no = ?", req.Apply_no).Find(&event)
	if event.Is_vaild != 0 || event.Status != common.APPROVAL_SUCCESS {
		w.WriteJson(message.GetErrorMsg(message.InValidOp, "审批单无效"))
		return
	}
	//判断用户是否是最后审批人
	var a_result approval.Approval_result_tbl
	orm.Where("apply_no = ?", req.Apply_no).Order("id desc").Limit(1).Find(&a_result)
	if a_result.Approver != username {
		w.WriteJson(message.GetErrorMsg(message.InValidOp, "用户不是最后审批人"))
		return
	}
	//审批提交内容
	mp := approval.GetApprovalContent(event.Content)

	//创建面试单
	ret, sheet_no := CreateInterviewSheet(req.Apply_no, req.Interviewer, req.Assistant, mp)
	if !ret {
		w.WriteJson(message.GetErrorMsg(message.UnknownError))
		return
	}
	//保存日志
	var logs oplog.Op_log_tbl
	logs.Operator = username
	logs.Topic = "面试"
	logs.Bundle = "出差面试"
	logs.Pid = "创建面试单"
	logs.Ip_addr = tools.GetClientIp(r.Request)
	logs.Attach0 = sheet_no //面试单号
	oplog.OpLogBaseAdd(logs)

	//TODO 通知面试官和助手
	msg := message.GetSuccessMsg()
	w.WriteJson(msg)
}

//查询面试官
func GetInterviewer(w rest.ResponseWriter, r *rest.Request) {
	var req GetInterviewerParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token, req.Apply_no) {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := user.GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}
	u, bb := user.GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}
	//权限检验
	b := auth.CheckRoleAuth(u.Business_role, auth_const.M_6, auth_const.L_A, auth_const.L_B, auth_const.L_C)
	if !b {
		w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
		return
	}
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	//判断审批单号是否有效
	var event approval.Approval_event_tbl
	orm.Where("apply_no = ?", req.Apply_no).Find(&event)
	if event.Is_vaild != 0 || event.Status != common.APPROVAL_SUCCESS {
		w.WriteJson(message.GetErrorMsg(message.InValidOp, "审批单无效"))
		return
	}
	//判断用户是否是最后审批人
	var a_result approval.Approval_result_tbl
	orm.Where("apply_no = ?", req.Apply_no).Order("id desc").Limit(1).Find(&a_result)
	if a_result.Approver != username {
		w.WriteJson(message.GetErrorMsg(message.InValidOp, "用户不是最后审批人"))
		return
	}

	var all []user.User_info_view

	sql := orm.Where("business_role not in (?)", auth_const.INVAILD_ROLE)
	if req.User_name != "" {
		sql = sql.Where("user = ?", req.User_name)
	}
	if req.Alias != "" {
		sql = sql.Where("alias like ?", "%"+req.Alias+"%")
	}
	if req.Role != 0 {
		sql = sql.Where("business_role = ?", req.Role)
	}
	sql.Find(&all)
	if len(all) > 0 {
		//审批提交内容
		mp := approval.GetApprovalContent(event.Content)
		start_time, _ := time.ParseInLocation("2006-01-02 15:04:05", strings.Split(mp["出差时间段"].Value, common.SPLIT)[0], time.Local)
		end_time, _ := time.ParseInLocation("2006-01-02 15:04:05", strings.Split(mp["出差时间段"].Value, common.SPLIT)[1], time.Local)

		for k, v := range all {
			var tmp []Interview_sheet_tbl
			orm.Where("person = ? and person_type = ? and start_time <= ?", v.User, 1, start_time).
				Or("person = ? and person_type = ? and end_time >= ?", v.User, 1, end_time).
				Find(&tmp)
			if len(tmp) > 0 {
				//已有面试，移除该用户
				all = append(all[:k], all[k+1:]...)
			}
		}
	}
	msg := message.GetSuccessMsg()
	msg.Data = all
	w.WriteJson(msg)

}
